<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
                :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="模板名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入模板名称" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="模板编码" prop="code">
            <el-input v-model="queryParams.code" placeholder="请输入模板编码" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="邮箱账号" prop="account">
            <el-select v-model="queryParams.accountId" placeholder="请选择邮箱账号" clearable>
              <el-option
                v-for="account in simpleMailAccount"
                :key="account.id"
                :value="account.id"
                :label="account.mail"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="开启状态" prop="status">
            <el-select v-model="queryParams.status" placeholder="请选择开启状态" clearable>
              <el-option
                v-for="dict in sys_mail_template"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="创建时间" style="width: 308px">
            <el-date-picker
              v-model="daterangeCreateTime"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:mailTemplate:add']">
              新增
            </el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="mailTemplateList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" align="center" prop="id" v-if="false" />
        <el-table-column label="模板名称" align="center" prop="name" />
        <el-table-column label="模板编码" align="center" prop="code" />
        <el-table-column label="邮箱账号" align="center" prop="accountId">
          <template v-slot="scope">
            <!--            {{ scope.row.accountId }}-->
            {{ getMailByAccountId(scope.row.accountId) }}
          </template>
        </el-table-column>
        <el-table-column label="发送人名称" align="center" prop="nickname" />
        <el-table-column label="模板标题" align="center" prop="title" />
        <el-table-column label="模板内容" align="center" prop="content" />
        <el-table-column label="开启状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="sys_mail_template" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="测试" placement="top">
              <el-button link type="primary" icon="Tools" @click="handleSend(scope.row.id)"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                         v-hasPermi="['system:mailTemplate:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                         v-hasPermi="['system:mailTemplate:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>
    <!-- 添加或修改邮件模版对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="800px" append-to-body>
      <el-form ref="mailTemplateFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="模板编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入模板编码" />
        </el-form-item>
        <el-form-item label="模板名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入模板标题" />
        </el-form-item>
        <el-form-item label="模板内容" prop="content">
          <editor v-model="form.content" :min-height="192" />
        </el-form-item>
        <el-form-item label="邮箱账号" prop="accountId">
          <el-select v-model="form.accountId" placeholder="请选择邮箱账号" clearable>
            <el-option
              v-for="account in simpleMailAccount"
              :key="account.id"
              :value="account.id"
              :label="account.mail"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发送人名称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入发送人名称" />
        </el-form-item>
        <el-form-item label="开启状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择开启状态">
            <el-option
              v-for="dict in sys_mail_template"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <!--        <el-form-item label="参数数组" prop="mailParams">-->
        <!--          <el-input v-model="form.mailParams" placeholder="请输入参数数组" />-->
        <!--        </el-form-item>-->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog title="测试" v-model="sendDialog" width="800px">
      <el-form ref="sendFormRef" :model="formData" :rules="formRules" label-width="140px">
        <el-form-item label="模板内容" prop="content">
          <Editor :model-value="formData.content" height="150px" readonly />
        </el-form-item>
        <el-form-item label="收件邮箱" prop="mail">
          <el-input v-model="formData.mail" placeholder="请输入收件邮箱" />
        </el-form-item>
        <el-form-item
          v-for="param in formData.mailParams"
          :key="param"
          :label="'参数 {' + param + '}'"
          :prop="'templateParams.' + param"
        >
          <el-input
            v-model="formData.templateParams[param]"
            :placeholder="'请输入 ' + param + ' 参数'"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :disabled="formLoading" type="primary" @click="submitSendForm">确 定</el-button>
          <el-button @click="sendCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="MailTemplate" lang="ts">
import {
  listMailTemplate,
  getMailTemplate,
  delMailTemplate,
  addMailTemplate,
  updateMailTemplate,
  sendMail
} from "@/api/mail/template";
import { MailTemplateVO, MailTemplateQuery, MailTemplateForm } from "@/api/mail/template/types";
import { ComponentInternalInstance } from "vue";
import { ElForm } from "element-plus";
import { getSimpleMailAccountList } from "@/api/mail/account";
import { SimpleMailAccount } from "@/api/mail/account/types";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_mail_template } = toRefs<any>(proxy?.useDict("sys_mail_template"));

const mailTemplateList = ref<MailTemplateVO[]>([]);
const simpleMailAccount = ref<SimpleMailAccount[]>([]);
const simpleMailAccountArray = computed(() => simpleMailAccount.value);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const daterangeCreateTime = ref([]);
const sendFormRef = ref();
const sendDialog = ref(false);
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用

const queryFormRef = ref(ElForm);
const mailTemplateFormRef = ref(ElForm);

const dialog = reactive<DialogOption>({
  visible: false,
  title: ""
});

const initFormData: MailTemplateForm = {
  id: "",
  name: "",
  code: "",
  accountId: "",
  nickname: "",
  title: "",
  content: "",
  mailParams: "",
  status: "",
  remark: ""
};
const data = reactive<PageData<MailTemplateForm, MailTemplateQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: "",
    code: "",
    accountId: "",
    status: "",
    createTime: ""
  },
  rules: {
    name: [
      { required: true, message: "模板名称不能为空", trigger: "blur" }
    ],
    code: [
      { required: true, message: "模板编码不能为空", trigger: "blur" }
    ],
    accountId: [
      { required: true, message: "发送的邮箱账号编号不能为空", trigger: "change" }
    ],
    content: [
      { required: true, message: "模板内容不能为空", trigger: "blur" }
    ],
    mailParams: [
      { required: true, message: "参数数组不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "开启状态不能为空", trigger: "change" }
    ]
  }
});

const formData = ref({
  content: "",
  mailParams: {},
  mail: "",
  templateCode: "",
  templateParams: new Map(),
  id: 0
});

const formRules = reactive({
  mail: [{ required: true, message: "邮箱不能为空", trigger: "blur" }],
  templateCode: [{ required: true, message: "模版编号不能为空", trigger: "blur" }],
  templateParams: {}
});

const { queryParams, form, rules } = toRefs(data);

/** 查询邮件模版列表 */
const getList = async () => {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeCreateTime && "" != daterangeCreateTime) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0];
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1];
  }
  const res = await listMailTemplate(queryParams.value);
  mailTemplateList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 获取邮箱数组信息 */
const getSimpleMailAccount = async () => {
  const res = await getSimpleMailAccountList();
  simpleMailAccount.value = res.data;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

const sendCancel = () => {
  resetForm();
  sendDialog.value = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  mailTemplateFormRef.value.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  daterangeCreateTime.value = [];
  queryFormRef.value.resetFields();
  handleQuery();
};

/** 发送消息表单重置 */
const resetForm = () => {
  formData.value = {
    content: "",
    mailParams: {},
    mail: "",
    templateCode: "",
    templateParams: new Map(),
    id: 0
  };
  formRules.templateParams = {};
  sendFormRef.value?.resetFields();
};
/** 多选框选中数据 */
const handleSelectionChange = (selection: MailTemplateVO[]) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

function getMailByAccountId(accountId: number) {
  const account = simpleMailAccountArray.value.find(item => item.id === accountId);
  return account ? account.mail : "";
};
/** 新增按钮操作 */
const handleAdd = () => {
  dialog.visible = true;
  dialog.title = "添加邮件模版";
  nextTick(() => {
    reset();
  });
};

/** 修改按钮操作 */
const handleUpdate = (row?: MailTemplateVO) => {
  loading.value = true;
  dialog.visible = true;
  dialog.title = "修改邮件模版";
  nextTick(async () => {
    reset();
    const _id = row?.id || ids.value[0];
    const res = await getMailTemplate(_id);
    loading.value = false;
    Object.assign(form.value, res.data);
  });
};

/** 测试按钮操作 */
const handleSend = async (id: number) => {
  sendDialog.value = true;
  resetForm();
  // 设置数据
  formLoading.value = true;
  try {
    const res = await getMailTemplate(id);
    const data = res.data;
    // 设置动态表单
    formData.value.content = data.content;
    formData.value.mailParams = data.mailParams;
    formData.value.templateCode = data.code;
    formData.value.id = data.id;
    formData.value.templateParams = data.mailParams.reduce((obj, item) => {
      obj[item] = ""; // 给每个动态属性赋值，避免无法读取
      return obj;
    }, {});
    formRules.templateParams = data.mailParams.reduce((obj, item) => {
      obj[item] = { required: true, message: "参数 " + item + " 不能为空", trigger: "blur" };
      return obj;
    }, {});
  } finally {
    formLoading.value = false;
  }
};

/** 提交按钮 */
const submitForm = () => {
  mailTemplateFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateMailTemplate(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addMailTemplate(form.value).finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      dialog.visible = false;
      await getList();
    }
  });
};
/** 提交发送邮件表单 */
const submitSendForm = async () => {
  // 校验表单
  if (!sendFormRef) return;
  const valid = await sendFormRef.value.validate();
  if (!valid) return;
  // 提交请求
  formLoading.value = true;
  try {
    const data = formData.value;
    const logId = await sendMail(data);
    proxy?.$modal.msgSuccess(logId.msg);
  } finally {
    sendDialog.value = false;
    formLoading.value = false;
  }
};


/** 删除按钮操作 */
const handleDelete = async (row?: MailTemplateVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm("是否确认删除邮件模版编号为\"" + _ids + "\"的数据项？").finally(() => loading.value = false);
  await delMailTemplate(_ids);
  proxy?.$modal.msgSuccess("删除成功");
  await getList();
};

onMounted(() => {
  getList();
  getSimpleMailAccount();
});
</script>
